package com.practice.heap;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:大顶堆
 * User: YJ
 * Date: 2023-10-25
 * Time: 20:06
 */
public class MaxHeap {
    int[] array;
    int size;

    public MaxHeap(int capacity) {
        this.array = new int[capacity];
    }

    //建堆
    private void heapify() {
        //找到最后一个非叶子节点  size / 2 - 1
        for (int i = size / 2 - 1; i >= 0; i--) {
            //下潜
            down(i);
        }
    }

    public MaxHeap(int[] array) {
        this.array = array;
        this.size = array.length;
        heapify();
    }

    /**
     * 删除堆顶元素
     * @return
     */
    public int poll() {
        return 0;
    }

    /**
     * 删除指定索引处元素
     * @param index
     * @return
     */
    public int poll(int index) {
        return 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peek() {
        return 0;
    }

    /**
     * 堆的尾部添加元素
     * @param offered
     * @return
     */
    public boolean offer(int offered) {
        return true;
    }

    /**
     * 元素上浮
     * @param offered
     */
    private void up(int offered) {

    }

    /**
     * 元素下潜(将parent索引处的元素下潜：与两个孩子较大者交换，直至没孩子或孩子没他大)
     * @param parent
     */
    private void down(int parent) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int max = parent;
        if (left < size && array[left] > array[max]) {
            max = left;
        }
        if (right < size && array[right] > array[max]) {
            max = right;
        }
        if (max != parent) {    //找到了更大的孩子
            //交换
            swap(parent,max);
            down(max);
        }
    }

    private void swap(int i,int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5,6,7};
        MaxHeap heap = new MaxHeap(arr);
        System.out.println(Arrays.toString(heap.array));
    }
}
